<template>
  <CDialog
    :visible="visible"
    title="忘记密码"
    width="630px"
    @submit="handleSubmit"
    @cancel="handleCancel"
    type="add"
  >
    <i-form :items="items" :model="form" :rules="rules" ref="form">
      <template slot="imgCode">
        <el-form-item label="图形验证码" prop="imgCode">
          <div class="autcode-content mobile-dialog-autcode_content">
            <el-input
              placeholder="请输入图形验证码"
              v-model="form.imgCode"
              class="authCode"
              :maxlength="4"
            />
            <div class="login-right_code mobile-dialog-autcode_content_right">
              <img class="code" :src="authCodeSrc" />
              <span class="create-code" @click="createCode">换一张</span>
            </div>
          </div>
        </el-form-item>
      </template>
      <template slot="code">
        <el-form-item label="验证码" prop="code">
          <div class="autcode-content mobile-dialog-autcode_content">
            <el-input
              placeholder="请输入验证码"
              class="authCode"
              v-model="form.code"
            />
            <div class="mobile-dialog-autcode_button">
              <HycTimerButton
                :user-mobile="form.mobile"
                :user-validation-code="form.imgCode"
                :convert-code-params="convertParams"
                @changeValidationCode="createCode"
              />
            </div>
          </div>
        </el-form-item>
      </template>
    </i-form>
  </CDialog>
</template>
<script>
import CDialog from '@/components/CDialog'
import md5 from 'md5'
import JSEncrypt from 'jsencrypt/bin/jsencrypt.min.js'
import { forgetPassword, getWebLoginImg } from '@/api/common'
import HycTimerButton from '@/components/hycTimerButton'
import formValidate from '@/utils/validate'
export default {
  name: 'ForgetPwd',
  components: { CDialog, HycTimerButton },
  props: {
    visible: {
      type: Boolean,
      required: true,
    },
  },
  mounted() {
    this.createCode()
  },
  data() {
    return {
      items: [
        {
          type: 'text',
          value: 'mobile',
          label: '手机号',
          clearable: true,
          placeholder: '请输入11位手机号码',
          required: true,
        },
        {
          slot: 'imgCode',
        },
        {
          slot: 'code',
        },
        {
          type: 'password',
          value: 'passWord1',
          label: '设置密码',
          'show-password': true,
          clearable: true,
          autoComplete: 'new-password',
          placeholder: '须包含数字、字母及特殊字符，长度不小于8位',
        },
        {
          type: 'password',
          value: 'passWord2',
          label: '确认密码',
          placeholder: '确认密码',
          autoComplete: 'off',
          'show-password': true,
          clearable: true,
        },
      ],
      form: {},
      rules: {
        mobile: [
          {
            required: true,
            message: '请输入手机号',
          },
          {
            validator: formValidate('validateMobile'),
            trigger: ['change', 'blur'],
          },
        ],
        passWord1: [
          { required: true, message: '请输入密码' },
          { validator: formValidate('validatePassword') },
        ],
        passWord2: [
          { required: true, message: '请输入确认密码' },
          {
            validator: (...args) => {
              if (args[1] !== this.form.passWord1) {
                args[2](new Error('两次密码不一致!'))
              } else {
                args[2]()
              }
            },
          },
        ],
      },
      convertParams: null,
      time: '',
      authCodeSrc: '',
    }
  },
  methods: {
    createCode() {
      this.time = new Date().getTime()
      const authCodeApi =
        process.env.VUE_APP_BASE_URL_API +
        '/open/getSystemUserLoginCerificationImg'
      this.authCodeSrc = `${authCodeApi}?uuid=${this.time}`
      getWebLoginImg({ rsa: true }).then((res) => {
        this.publicKey = res.headers && res.headers['rsa-public-key']
        this.checkKey = res.headers && res.headers['rsa-check-key']
        localStorage.setItem('checkKey', this.checkKey)
        let reader = new FileReader()
        reader.readAsDataURL(res.data)
        reader.onload = (evt) => {
          let imageString = evt.target.result
          this.authCodeSrc = imageString
        }
      })
    },
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (!valid) return
        let encryptor = new JSEncrypt()
        encryptor.setPublicKey(this.publicKey)
        let p = encryptor.encrypt(md5(this.form.passWord1))
        let params = {
          code: this.form.code,
          mobile: this.form.mobile,
          // passWord1: encryptor.encrypt(md5(this.form.passWord1)),
          // passWord2: encryptor.encrypt(md5(this.form.passWord2)),
          passWord1: p,
          passWord2: p,
        }

        forgetPassword(params).then(() => {
          this.$message({
            showClose: true,
            message: '重置密码成功',
            type: 'success',
          })

          this.$emit('update:visible', false)
        })
      })
    },
    handleCancel() {
      this.$emit('update:visible', false)
    },
  },
}
</script>
<style lang="scss" scoped>
.mobile-dialog-autcode_content {
  display: flex;

  .mobile-dialog-autcode_content_right {
    margin-left: 20px;
    display: flex;
    min-width: 188px;
    max-width: 188px;

    img {
      width: 100px;
      height: 40px;
    }
  }

  .create-code {
    margin-left: 14px;
    cursor: pointer;
  }
}

.mobile-dialog-autcode_button {
  .el-button {
    margin-left: 40px;
    margin-right: 28px;
    height: 40px;
  }
}
</style>
